package renguanyu.app.tools.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;

public class SqlToStringbuiderController {

	@FXML
	TextField variable;
	@FXML
	TextArea sourceSql;
	@FXML
	TextArea targetStringbuilder;
	@FXML
	TextArea sourceStringbuilder;
	@FXML
	TextArea targetSql;

	@FXML
	public void sqlToStringbuilder() {
		List<String> result = new ArrayList<>();
		String sqlStr = sourceSql.getText();
		String[] sqlArray = sqlStr.split("\n");
		String tempVar = "sql";
		if (!variable.getText().isEmpty()) {
			tempVar = variable.getText();
		}
		result.add("StringBuilder " + tempVar + " = new StringBuilder();");
		for (int i = 0; i < sqlArray.length; i++) {
			result.add("" + tempVar + ".append(\"" + sqlArray[i] + " \");");
		}
		targetStringbuilder.clear();
		result.forEach(data -> {
			targetStringbuilder.appendText(data);
			targetStringbuilder.appendText("\n");
		});
	}

	@FXML
	public void stringbuilderToSql() {
		String REGEX = "append\\(\"(.*)\"\\);";
		List<String> result = new ArrayList<>();
		String stringBuilderStr = sourceStringbuilder.getText();
		Pattern p = Pattern.compile(REGEX);
		String[] rowArray = stringBuilderStr.split("\n");
		for (int i = 0; i < rowArray.length; i++) {
			String row = rowArray[i];
			Matcher m = p.matcher(row);
			while (m.find()) {
				String content = m.group(1);
				result.add(content);
			}
		}
		targetSql.clear();
		for (int i = 0; i < result.size(); i++) {
			String newStr = result.get(i);
			targetSql.appendText(newStr);
			targetSql.appendText("\n");
		}
	}

}
